package com.ftp.web.spider.parser;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ImageParser {
	
	public enum requestTypes{
	 get,
	 post
	}
	
	static String attrString="ess-data";

	/***
	 * 打开链接
	 * @param link
	 * @param method
	 * @return
	 */
	public  Map openLinks(String link,String method) {
		Document doc=null;
		try {
			
			if(method.equals("get")) {
				doc=Jsoup.connect(link).get();
			}
			
			if(method.equals("post")) {
				doc=Jsoup.connect(link).post();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return this.parseDoc(doc);
	}
	
	public  Map parseDoc(Document document) {
		Map<String,List> map=new HashMap<String, List>();
		Elements elements=document.getElementsByTag("img");
		String imgsKeyString=document.title();
		imgsKeyString=imgsKeyString.substring(imgsKeyString.indexOf("["), imgsKeyString.lastIndexOf("]")+1);
		imgsKeyString=imgsKeyString.substring(imgsKeyString.indexOf("]")+1,imgsKeyString.lastIndexOf("[")).trim();
		List list=new ArrayList<String>();
		for (Element element : elements) {
			if(element.hasAttr(attrString)) {
				list.add(element.attr(attrString));
				System.out.println(element.attr(attrString));
			}
		}
		map.put(imgsKeyString, list);
		return map;
		
	}
	
	
	
}
